package com.heba.adapter.diary;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.adapter.diary.callback.DiaryItemListener;
import com.heba.banner.ViewPagerFocusView;
import com.heba.bean.diary.ItemDiaryCommentObject;
import com.heba.bean.diary.ItemDiaryDetailObject;
import com.heba.bean.diary.ItemDiaryImageObject;
import com.heba.bean.diary.ItemDiaryTagObject;
import com.heba.bean.diary.ItemTagInfoObject;
import com.heba.bean.diary.ItemUserInfoObject;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.MainActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.businesslist.BusinessHomePageActivity;
import com.heba.greenmulu.businesslist.BusinessPersonActivity;
import com.heba.greenmulu.diary.ItemDiaryCommentActivity;
import com.heba.greenmulu.diary.ItemDiaryLikeListActivity;
import com.heba.greenmulu.diary.ItemPersonHomePageActivity;
import com.heba.greenmulu.hashtag.ItemHashTagPageActivity;
import com.heba.greenmulu.message.ItemMessageSendActivity;
import com.heba.greenmulu.scan.ItemProductDetailActivity;
import com.heba.helper.DateHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.popupwindow.OpenMapPopupWindow;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.view.FlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

/**
 * 日记列表recyclerAdapter
 * Created by jason on 2020/5/26.
 */
public class DiaryListRecyclerAdapter extends QuickAdapter<ItemDiaryDetailObject> {

    private Context context;

    private HashMap<Integer, Integer> mViewPageStates;

    private DiaryItemListener listener;

    private Location location;

    public OpenMapPopupWindow openMapPopupWindow;
    public DiaryListRecyclerAdapter(Context context, List<ItemDiaryDetailObject> datas) {
        super(datas);
        this.context = context;
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        mViewPageStates = new HashMap<>();
    }

    /**
     * 设置监听接口
     *
     * @param listener
     */
    public void setDiaryItemListener(DiaryItemListener listener) {
        this.listener = listener;
    }

    public void setLocation(Location location) {
        this.location = location;
    }

    @Override
    public int getLayoutId(int viewType) {
        return R.layout.recycle_item_diary_row;
    }

    @Override
    public void onViewRecycled(@NonNull VH holder) {
        super.onViewRecycled(holder);
        ViewPager viewPager = holder.getView(R.id.viewPager);
        mViewPageStates.put(holder.getAdapterPosition(), viewPager.getCurrentItem());
    }


    @Override
    public void convert(VH holder, ItemDiaryDetailObject data, int position) {
        /**
         * 彈出分享框
         */
        ImageView iv_more = holder.getView(R.id.iv_more);
        iv_more.setOnClickListener(v -> {
            if (null != listener) {
                listener.showSharePopup(v, position, data);
            }
        });

        /**
         * 显示日记数据
         */
        TextView iv_lookNumber = holder.getView(R.id.iv_lookNumber);
        ImageView iv_avatar = holder.getView(R.id.iv_avatar);
        TextView tv_prodyct = holder.getView(R.id.tv_product);
        GlideUtil.loadImageWithPlaceHolderID(context, data.getIcon(), iv_avatar, R.drawable.icon_head_portrait);
        holder.setText(R.id.tv_name, data.getAccount());
        holder.setText(R.id.tv_time, DateHelper.transferDateString(context, data.getTimeCreated()));
        holder.setText(R.id.tv_place,data.getPlace());
        TextView placeTV = holder.getView(R.id.tv_place);
        placeTV.setOnClickListener(v->{
            openMapPopupWindow.setDiaryDetailObject(data);
            openMapPopupWindow.setmLocation(location);
            openMapPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        });
//        holder.setText(R.id.tv_desc, CommonUtils.getDecodeText(data.getContent()));
        String diaryText = CommonUtils.getDecodeText(data.getContent());
//        diaryText = diaryText.replaceAll("@","<font color=\"#333333\">@</font>");
//        diaryText = diaryText.replaceAll("#","<font color=\"#333333\">#</font>");
//        StringBuffer buffer = new StringBuffer();
//        if (data.getUserList() != null){
//            for(int i = 0;i<data.getUserList().size();i++){
//                ItemUserInfoObject obj = data.getUserList().get(i);
//                diaryText = diaryText.replaceAll("@"+obj.getAccount(),"<font color=\"#333333\">@</font>"+"<font color=\"#95CF63\">"+obj.getAccount()+"</font>");
//            }
//        }
//        if (data.getTalkList() != null){
//            for (int i = 0 ; i <data.getTalkList().size();i++){
//                ItemDiaryTagObject obj = data.getTalkList().get(i);
//                diaryText = diaryText.replaceAll(obj.getContent(),"<font color=\"#333333\">#</font>"+"<font color=\"#95CF63\">"+obj.getContent().split("#")[1]+"</font>");
//            }
//        }
        StringBuffer buffer = new StringBuffer();
        buffer.append(diaryText);

        SpannableStringBuilder ssb = new SpannableStringBuilder();

//        if (data.getUserList() != null){
//            for (int i = 0;i < data.getUserList().size();i++){
//                ItemUserInfoObject obj = data.getUserList().get(i);
//                buffer.replace(buffer.indexOf(obj.getAccount()),buffer.indexOf(obj.getAccount())+obj.getAccount().length(),"<font color=\"#95CF63\">"+obj.getAccount()+"</font>");
//
//            }
//        }
        if (data.getUserList() != null){
            for(int i = 0;i<data.getUserList().size();i++){
                ItemUserInfoObject obj = data.getUserList().get(i);
                diaryText = diaryText.replaceAll("@"+obj.getAccount(),"<font color=\"#95CF63\">@</font>"+"<font color=\"#95CF63\">"+obj.getAccount()+"</font>");
            }
        }
        if (data.getTalkList() != null){
            for (int i = 0 ; i <data.getTalkList().size();i++){
                ItemDiaryTagObject obj = data.getTalkList().get(i);
                int index = buffer.indexOf(obj.getContent());
                if (index != -1){
                    buffer.replace(buffer.indexOf(obj.getContent())+1,buffer.indexOf(obj.getContent())+1+obj.getContent().length(),"<font color=\"#95CF63\">"+obj.getContent().split("#")[1]+"</font>");

                }
            }
        }
//        diaryText = buffer.toString();
        ssb.append(Html.fromHtml(diaryText));
        String htmlString =  Html.fromHtml(diaryText).toString();
        TextView textView = holder.getView(R.id.tv_desc);
        if (data.getUserList() != null){
            for (int i = 0;i < data.getUserList().size();i++){
                ItemUserInfoObject obj = data.getUserList().get(i);

                ssb.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        Bundle bundle = new Bundle();
                        bundle.putString(CommonConfig.SEND_USER_ID, obj.getUserID());
                        if (obj.getAccountType().equals("0") ){

                            openActivity(ItemPersonHomePageActivity.class, bundle);
                        }else{
                            openActivity(BusinessPersonActivity.class, bundle);
                        }
                    }
                    @Override
                    public void updateDrawState(TextPaint ds) {
                        ds.setUnderlineText(false);
                    }
                },htmlString.indexOf("@"+obj.getAccount().charAt(0))+1,htmlString.indexOf("@"+obj.getAccount().charAt(0))+obj.getAccount().length(),0);
            }
        }

        if (data.getTalkList() != null){
            for (int i = 0 ; i <data.getTalkList().size();i++){
                ItemDiaryTagObject obj = data.getTalkList().get(i);
                int index = htmlString.indexOf(obj.getContent());
                if (index != -1){


                    ssb.setSpan(new ClickableSpan() {
                        @Override
                        public void onClick(@NonNull View widget) {
                            Bundle bundle = new Bundle();
                            bundle.putString(CommonConfig.HASHTAG_ID, obj.getHashtagID());
                            openActivity(ItemHashTagPageActivity.class, bundle);

                        }
                        @Override
                        public void updateDrawState(TextPaint ds) {
                            ds.setUnderlineText(false);
                        }
                    },htmlString.indexOf(obj.getContent().charAt(0)),htmlString.indexOf(obj.getContent().charAt(0))+obj.getContent().length(),0);

                }
            }
        }
        textView.setHighlightColor(ContextCompat.getColor(context,R.color.transparent));
        textView.setMovementMethod(LinkMovementMethod.getInstance());//加上这句话才有效果
        textView.setText(ssb,TextView.BufferType.SPANNABLE);
        iv_lookNumber.setText(String.format(context.getResources().getString(R.string.scan_product_comment_views), data.getViews()));
        tv_prodyct.setVisibility(data.getProductID().equals("0") ? View.INVISIBLE : View.VISIBLE);

        /**
         * 跳转产品详情页
         */
        tv_prodyct.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString(CommonConfig.PRODUCT_ID, data.getProductID());
            openActivity(ItemProductDetailActivity.class, bundle);
        });

        /**
         * 查看用户个人资料
         */
        iv_avatar.setOnClickListener(v -> {
            if (data.getAccountType()== 0){
                Bundle bundle = new Bundle();
                bundle.putString(CommonConfig.SEND_USER_ID, data.getUserID());
                openActivity(BusinessPersonActivity.class, bundle);
            }else{
                Bundle bundle = new Bundle();
                bundle.putString(CommonConfig.SEND_USER_ID, data.getUserID());
                openActivity(BusinessPersonActivity.class, bundle);
            }
        });

        /**
         * 設置圖片资源
         */
//      Banner banner = holder.getView(R.id.viewPager);
        ConstraintLayout constraintLayout = holder.getView(R.id.constrain_view);
        ViewPager viewPager = holder.getView(R.id.viewPager);
        ViewPagerFocusView focusView = holder.getView(R.id.viewpger_focusview);
        ImageView iv_play = holder.getView(R.id.iv_play);
//      ImageView iv_show_tag = holder.getView(R.id.iv_show_tag);
        ImageView iv_send = holder.getView(R.id.iv_send);
        ImageView iv_like = holder.getView(R.id.iv_like);
        constraintLayout.setVisibility(View.VISIBLE);
//        ConstraintLayout content_view = holder.getView(R.id.content_view);



        iv_play.setVisibility(View.GONE);
//        iv_show_tag.setVisibility(View.GONE);
        if (!data.getImageList().isEmpty()) {
            focusView.setCount(data.getImageList().size(), R.drawable.guide_point_select, R.drawable.icon_diary_slideshow_s);
            List<ItemDiaryImageObject> imageObjects = data.getImageList();
//                    banner.setImages(imageObjects)
//                            .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
//                            .setImageLoader(new GlideImageLoader())
//                            .isAutoPlay(false)
//                            .start();
            DiaryImageShowPagerAdapter viewpagerAdapter = new DiaryImageShowPagerAdapter(context, imageObjects,data,position,iv_like);
            viewPager.setAdapter(viewpagerAdapter);

            //显示视频
            if (imageObjects.size() == 1 && imageObjects.get(0).getType() == 1) {
                iv_play.setVisibility(View.VISIBLE);

            }
            if (imageObjects.size() == 1){
                focusView.setVisibility(View.GONE);
            }else{
                focusView.setVisibility(View.VISIBLE);
            }
        } else {
            constraintLayout.setVisibility(View.GONE);
            focusView.setVisibility(View.GONE);
        }

        //获取viewpager item位置
        if (mViewPageStates.containsKey(position)) {
            viewPager.setCurrentItem(mViewPageStates.get(position));
        }

        /**
         * viewpager监听
         */
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                focusView.setCurrentIndex(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        /**
         * 判断有无标记朋友
         */
//        for (int i = 0; i < data.getImageList().size(); i++) {
//            if (data.getImageList().get(i).getPaste() != null && !data.getImageList().get(i).getPaste().isEmpty()) {
//                iv_show_tag.setVisibility(View.VISIBLE);
//                break;
//            }
//        }

        /**
         * 添加標籤
         */
        FlowLayout fl_tag_view = holder.getView(R.id.fl_tag_view);
        updateFlowView(fl_tag_view, data.getTalkList());

        /**
         * 留言、點讚、传送view显示
         */

//       ImageView et_comment = holder.getView(R.id.et_comment);
        ImageView et_comment_icon = holder.getView(R.id.et_comment_icon);


        holder.setText(R.id.tv_like_num, data.getLikeCount() + "");
        //設置edittex不允許編輯
//        et_comment.setFocusable(false);
//        et_comment.setFocusableInTouchMode(false);
//        et_comment.setHint(String.format(context.getResources().getString(R.string.diary_reply_hint), data.getAccount()));
        iv_like.setSelected(data.getIsLiked() == 1);

        /**
         * 彈出評論框
         */
        et_comment_icon.setOnClickListener(v -> {
            if (null != listener) {
                listener.showCommentPopup(v, data.getDiaryID(), data.getUserID());
            }
        });
        /**
         * 點讚或取消點讚事件監聽
         */
        iv_like.setOnClickListener(v -> {
            //不能自己點讚自己，跳轉點讚列表
            if (Cfg.UserID.equals(data.getUserID())) {
                Bundle bundle = new Bundle();
                bundle.putString(CommonConfig.DIARY_ID, data.getDiaryID());
                bundle.putInt(CommonConfig.LIKE_COUNT, data.getLikeCount());
                openActivity(ItemDiaryLikeListActivity.class, bundle);
                return;
            }

            new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                @Override
                public void Success() {
                    if (data.getIsLiked() == 1) {
                        data.setIsLiked(0);
                        data.setLikeCount(data.getLikeCount() - 1);
                        iv_like.setSelected(false);
                    } else {
                        data.setIsLiked(1);
                        data.setLikeCount(data.getLikeCount() + 1);
                        iv_like.setSelected(true);
                    }
                    notifyItemChanged(position);
                }

                @Override
                public void Fail(String error) {

                }
            }).diaryLike(context, data.getDiaryID(), data.getIsLiked());
        });

        /**
         * 傳送日記專頁
         */
        iv_send.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putInt(CommonConfig.TYPE, CommonConfig.TYPE_SEND_DIARY);
            bundle.putString(CommonConfig.MESSAGE_ID, data.getDiaryID());
            openActivity(ItemMessageSendActivity.class, bundle);
        });


        /**
         * 显示日记评论数据
         */
        View view_comment = holder.getView(R.id.view_comment);
        LinearLayout ll_comment_view = view_comment.findViewById(R.id.ll_comment_view);
        updateCommentView(ll_comment_view, data.getDiaryID(), data.getFeedbackCount(), data.getFeedback());

        /**
         * 跳轉到日記評論頁面
         */
        holder.itemView.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString(CommonConfig.DIARY_ID, data.getDiaryID());
            openActivity(ItemDiaryCommentActivity.class, bundle);
        });
    }

    /**
     * 更新流式佈局
     *
     * @param flowLayout
     * @param tags
     */
    private void updateFlowView(FlowLayout flowLayout, List<ItemDiaryTagObject> tags) {
        flowLayout.removeAllViews();

        if (tags == null)
            return;

        /**
         * 添加佈局參數
         */
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(context, 20));
//        params.rightMargin = DensityUtils.dip2px(context, 8);
//        params.bottomMargin = DensityUtils.dip2px(context, 3);
//        for (int i = 0; i < tags.size(); i++) {
//            flowLayout.addView(updateFlowRowView(tags.get(i)), params);
//        }
    }

    /**
     * 添加item佈局
     */
    private View updateFlowRowView(ItemDiaryTagObject object) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_tag_flow_row, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        tv_text.setText(object.getContent());

        view.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString(CommonConfig.HASHTAG_ID, object.getHashtagID());
            openActivity(ItemHashTagPageActivity.class, bundle);
        });
        return view;
    }

    /**
     * 更新日记评论布局
     *
     * @param ll_comment_view
     * @param diaryID
     * @param commentCount
     * @param commentObjectList
     */
    private void updateCommentView(LinearLayout ll_comment_view, String diaryID, int commentCount, List<ItemDiaryCommentObject> commentObjectList) {
        ll_comment_view.removeAllViews();

        if (commentObjectList == null)
            return;

        /**
         * 添加評論item
         */
        for (int i = 0; i < commentObjectList.size(); i++) {
            ll_comment_view.addView(updateCommentRowView(diaryID, commentObjectList.get(i)));
        }

        /**
         * 添加更多評論的view
         */
        if (commentCount > commentObjectList.size()) {
            ll_comment_view.addView(updateMoreCommentRowView(diaryID, commentCount));
        }
    }

    /**
     * 添加评论item布局
     *
     * @return
     */
    private View updateCommentRowView(String diaryID, ItemDiaryCommentObject object) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_diary_comment_row, null);
        TextView tv_comment = view.findViewById(R.id.tv_comment);
        String commentStr = "<strong>" + object.getAccount() + "&nbsp;&nbsp;" + "</strong>" + CommonUtils.getDecodeText(object.getMessage());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tv_comment.setText(Html.fromHtml(commentStr, Html.FROM_HTML_MODE_COMPACT));
        } else {
            tv_comment.setText(Html.fromHtml(commentStr));
        }
        /**
         * 查看更多評論
         */
        view.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString(CommonConfig.DIARY_ID, diaryID);
            openActivity(ItemDiaryCommentActivity.class, bundle);
        });
        return view;
    }

    /**
     * 添加更多評論的view
     *
     * @param diaryID
     * @param count
     * @return
     */
    private View updateMoreCommentRowView(String diaryID, int count) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_diary_more_text_row, null);
        TextView tv_more_comment = view.findViewById(R.id.tv_more_comment);
        tv_more_comment.setText(String.format(context.getResources().getString(R.string.diary_comment_more), count));
        /**
         * 查看更多評論
         */
        view.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString(CommonConfig.DIARY_ID, diaryID);
            openActivity(ItemDiaryCommentActivity.class, bundle);
        });
        return view;
    }

    /**
     * 跳转activity
     *
     * @param pClass
     * @param pBundle
     */
    private void openActivity(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(context, pClass);
        intent.putExtras(pBundle);
        context.startActivity(intent);
        ((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    /**
     * 跳转activity
     *
     * @param pClass
     * @param pBundle
     */
    private void openActivityWithFadeInAnimation(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(context, pClass);
        intent.putExtras(pBundle);
        context.startActivity(intent);
        ((Activity) context).overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 接收事件
         */
        if (event.getEvent().equals("DoubleClickToLike")) {
            int position = event.getPosition();
            notifyDataSetChanged();
//            notifyItemChanged(position);

            //不能自己點讚自己，跳轉點讚列表



        }
    }
}
